/**
 * Created with IntelliJ IDEA.
 * Description:二叉搜索树
 * User: LianBao
 * Date: 2024-04-23
 * Time: 12:38
 */
public class Tree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;


    //二叉搜索树的查找
    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val < key) {
                cur = cur.right;
            } else if (cur.val > key) {
                cur = cur.left;
            } else {
                return cur;
            }
        }
        return null;
    }

    //二叉搜索树的插入->一定是插入在叶子结点
    public void Insert(int key) {
        TreeNode newNode = new TreeNode(key);
        if (root == null) {
            //第一次插入
            root = newNode;
        }
        TreeNode cur = root;
        TreeNode curP = null;
        while (cur != null) {
            if (cur.val > key) {
                curP = cur;
                cur = cur.right;
            } else {
                curP = cur;
                cur = cur.left;
            }
        }
        if (curP.val < key) {
            curP.right = newNode;
        } else {
            curP.left = newNode;
        }
    }

    //二叉搜索树删除
    public void Delete(int key) {
        if (root == null) {
            return;
        }
        TreeNode delP = null;
        TreeNode del = root;
        while (del != null) {
            if (del.val > key) {
                delP = del;
                del = del.left;
            } else if (del.val < key) {
                delP = del;
                del = del.right;
            } else {
                //找到了del,开始删除结点
                removeNode(del, delP);
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode del) {
        //三种情况

        //1.删除的结点的left为空
        if (del.left == null) {
            if (del == root) {
                //1.1 删除的结点是根节点(root)
                root = del.right;
            } else if (del == parent.left) {
                //1.2 删除的结点不是root,删除的结点是parent.left
                parent.left = del.right;
            } else {
                //1.3 删除的结点不是root,删除的结点是parent.right
                parent.right = del.right;
            }

        } else if (del.right == null) {
            //2.删除的结点的right为空
            if (del == root) {
                //2.1 删除的结点是根节点(root)
                root = del.left;
            } else if (del == parent.left) {
                //2.2 删除的结点是parent.left
                parent.left = del.left;
            } else {
                //2.3 删除的结点是parent.right
                parent.right = del.left;
            }
        } else {
            //3.删除的结点左右都不为空
        }
    }
}
